package com.gy.paidao.main;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.gy.paidao.BaseActivity;
import com.gy.paidao.R;
import com.gy.paidao.bean.BaseBean;
import com.gy.paidao.main.adapter.BabblesDetailAdapter;
import com.gy.paidao.main.bean.ActivityBean;
import com.gy.paidao.main.bean.CommentBean;
import com.gy.paidao.util.AnimUtil;
import com.gy.paidao.util.KeyBoard;
import com.gy.paidao.util.LogUtil;
import com.gy.paidao.util.SPHelper;
import com.gy.paidao.util.Urls;
import com.gy.paidao.view.SwipeMenu;
import com.gy.paidao.view.SwipeMenuCreator;
import com.gy.paidao.view.SwipeMenuItem;
import com.gy.paidao.view.SwipeMenuListView;
import com.jky.struct2.http.core.AjaxParams;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者：gy on 16/4/14
 * 说明：泡泡详情
 */
public class BabbleDetailActivity extends BaseActivity {

    private RelativeLayout rlMain,rlButtom;
    private View viewHead,viewComment;
    private SwipeMenuListView mListView;
    private ImageView imgLeft,imgRight,imgHead,imgTopLeft,imgBg;
    private TextView tvTitle,tvContent,tvLoc,tvFire,tvConmmentNum,
            tvComments,tvSure,tvInput,tvEmpty;
    private EditText etComment;
    private LinearLayout llFire,llComment,llDelete,llComments;
    private BabblesDetailAdapter adapter;
    private PopupWindow popupWindow;
    private ActivityBean activityBean;//泡泡详情
    private Dialog reportDialog;
    private List<CommentBean> listComment,listRequest;
    private String userLoginID;
    private int intoFlag;//进入标识  1为评论

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_babble_detail);
        setViews();
        dorequestCommenList();
        showRequestLoading();
    }

    @Override
    protected void initVariable() {
        intoFlag = getIntent().getIntExtra("intoDetail",0);
        userLoginID = SPHelper.getInstance(this).getStringData("userLoginID",null);
        activityBean = (ActivityBean) getIntent().getSerializableExtra("activity");
        listComment = new ArrayList<>();
        listRequest = new ArrayList<>();
        adapter = new BabblesDetailAdapter(this,listComment);
    }

    @Override
    protected void setTitleViews() {

    }

    @Override
    protected void setViews() {
        rlMain = (RelativeLayout) findViewById(R.id.activity_detail_rl_main);
        rlButtom = (RelativeLayout) findViewById(R.id.activity_detail_rl_bottom);
        viewHead = View.inflate(this,R.layout.view_babble_detail,null);
        viewComment = View.inflate(this,R.layout.view_detail_input_comment,null);
        imgBg = (ImageView) viewHead.findViewById(R.id.view_babble_top_img_bg);
        imgLeft = (ImageView) viewHead.findViewById(R.id.view_babble_top_img_left);
        imgRight = (ImageView) viewHead.findViewById(R.id.view_babble_top_img_right);
        imgHead = (ImageView) viewHead.findViewById(R.id.view_babble_top_img_head);
        tvTitle = (TextView) viewHead.findViewById(R.id.view_babble_top_tv_title);
        tvContent = (TextView) viewHead.findViewById(R.id.view_babble_top_tv_content);
        tvLoc = (TextView) viewHead.findViewById(R.id.view_babble_top_tv_loc);
        tvFire = (TextView) viewHead.findViewById(R.id.view_babble_top_tv_fire);
        tvConmmentNum = (TextView) viewHead.findViewById(R.id.view_babble_top_tv_comment);
        tvComments = (TextView) viewHead.findViewById(R.id.view_babble_top_tv_comments);
        llFire = (LinearLayout) viewHead.findViewById(R.id.view_babble_top_ll_fire);
        llComment = (LinearLayout) viewHead.findViewById(R.id.view_babble_top_ll_comment);
        llDelete = (LinearLayout) viewHead.findViewById(R.id.view_babble_top_ll_delete);
        imgTopLeft = (ImageView) findViewById(R.id.activity_detail_img_left);
        tvInput = (TextView) findViewById(R.id.activity_detail_tv_input);
        tvSure = (TextView) viewComment.findViewById(R.id.activity_detail_tv_sure);
        tvEmpty = (TextView) viewComment.findViewById(R.id.activity_detail_tv_empty);
        etComment = (EditText) viewComment.findViewById(R.id.activity_detail_et_comment);
        llComments = (LinearLayout) findViewById(R.id.activity_detail_ll_comments);
        mListView = (SwipeMenuListView) findViewById(R.id.activity_detail_listview);
        mListView.addHeaderView(viewHead);
        mListView.setAdapter(adapter);

        imgBg.setOnClickListener(this);
        rlButtom.setOnClickListener(this);
        tvInput.setOnClickListener(this);
        tvEmpty.setOnClickListener(this);
        tvSure.setOnClickListener(this);
        imgTopLeft.setOnClickListener(this);
        imgLeft.setOnClickListener(this);
        imgRight.setOnClickListener(this);
        llFire.setOnClickListener(this);
        llComment.setOnClickListener(this);
        llDelete.setOnClickListener(this);

        SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {
                SwipeMenuItem openItem = new SwipeMenuItem(
                        getApplicationContext());
                openItem.setBackground(new ColorDrawable(Color.parseColor("#767676")));
                openItem.setWidth(dp2px(90));
                openItem.setTitle(getResources().getString(R.string.report));
                openItem.setTitleSize(15);
                openItem.setTitleColor(Color.WHITE);
                menu.addMenuItem(openItem);
            }
        };
        mListView.setMenuCreator(creator);
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (viewHead.getTop() != 0 && viewHead.getHeight() != 0) {
                    if (viewHead.getTop() + viewHead.getHeight() <= tvComments.getHeight()) {
                        llComments.setVisibility(View.VISIBLE);
                    } else {
                        llComments.setVisibility(View.GONE);
                    }
                }

//                LogUtil.e(firstVisibleItem+"  "+visibleItemCount+"  "+totalItemCount);
            }
        });
        mListView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:
                        intent = new Intent(BabbleDetailActivity.this,ReportActivity.class);
                        intent.putExtra("id",listComment.get(index).id+"");
                        if("image".equals(activityBean.mediaType)){
                            intent.putExtra("path",activityBean.mediaPaths);
                        } else if("video".equals(activityBean.mediaType)){
                            intent.putExtra("path",activityBean.thumbnailUrl);
                        }
                        intent.putExtra("intoFlag",0);
                        startActivity(intent);
                        AnimUtil.pushLeftInAndOut(BabbleDetailActivity.this);
                        break;
                }
                return false;
            }
        });
        initPop();
        setDatas();

    }

    private void setDatas(){
        if(activityBean != null){
            tvTitle.setText(activityBean.title+"");
            tvContent.setText(activityBean.description+"");
            tvLoc.setText(activityBean.position+"");
            tvFire.setText(activityBean.heatValue+"");
            tvConmmentNum.setText(activityBean.commentNum+"");

            if(!TextUtils.isEmpty(activityBean.headPortrait)){
                ImageLoader.getInstance().displayImage(activityBean.headPortrait,imgHead);
            }

            if("image".equals(activityBean.mediaType)){
                if(!TextUtils.isEmpty(activityBean.mediaPaths)){
                    ImageLoader.getInstance().displayImage(activityBean.mediaPaths,imgBg);
                }
            } else if("video".equals(activityBean.mediaType)){
                if(!TextUtils.isEmpty(activityBean.mediaPaths)){
                    ImageLoader.getInstance().displayImage(activityBean.thumbnailUrl,imgBg);
                }
            }
        }
    }

    @Override
    protected void doClickAction(int viewId) {
        super.doClickAction(viewId);
        switch (viewId){
            case R.id.activity_detail_img_left:
            case R.id.view_babble_top_img_left:
                this.finish();
                AnimUtil.pushRightInAndOut(this);
                break;
            case R.id.view_babble_top_img_right:
                showReportDialog();
                break;
            case R.id.view_babble_top_img_bg:
                intent = new Intent(this,BubbleDetailInfoActivity.class);
                intent.putExtra("path",activityBean.mediaPaths+"");
                intent.putExtra("flag",activityBean.mediaType+"");
                intent.putExtra("id",activityBean.id+"");
                startActivity(intent);
                break;
            case R.id.activity_detail_tv_input:
                etComment.setFocusable(true);
                etComment.setFocusableInTouchMode(true);
                etComment.requestFocus();
                KeyBoard.showKeyBoard(this,etComment);
                InputMethodManager inputManager = (InputMethodManager) etComment
                        .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(etComment, 0);
                popupWindow.showAtLocation(this.getCurrentFocus(), Gravity.BOTTOM, 0, 0);
                break;
            case R.id.activity_detail_tv_empty:
                popupWindow.dismiss();
                break;
            case R.id.view_babble_top_ll_fire://热火
                if(activityBean.heated == 0){
                    dorequestFire(activityBean.id+"");
                }
                break;
            case R.id.view_babble_top_ll_comment://评论
                etComment.setFocusable(true);
                etComment.setFocusableInTouchMode(true);
                etComment.requestFocus();
                KeyBoard.showKeyBoard(this,etComment);
                inputManager = (InputMethodManager) etComment
                        .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(etComment, 0);
                popupWindow.showAtLocation(this.getCurrentFocus(), Gravity.BOTTOM, 0, 0);
                break;
            case R.id.view_babble_top_ll_delete://删除
                dorequestDelete(activityBean.id+"");
                break;
            case R.id.activity_detail_tv_sure://评论确定
                String comment = etComment.getText().toString().trim();
                if(TextUtils.isEmpty(comment)){
                    showToast("请输入评论内容");
                } else {
                    etComment.setText("");
                    dorequestComment(comment);
                }
                break;
            case R.id.dialog_report_bubble://进入评论
                intent = new Intent(BabbleDetailActivity.this,ReportActivity.class);
                intent.putExtra("id",activityBean.id+"");
                intent.putExtra("intoFlag",1);
                if("image".equals(activityBean.mediaType)){
                    intent.putExtra("path",activityBean.mediaPaths);
                } else if("video".equals(activityBean.mediaType)){
                    intent.putExtra("path",activityBean.thumbnailUrl);
                }
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(BabbleDetailActivity.this);
                reportDialog.dismiss();
                break;
            case R.id.dialog_report_picture://进入评论
                intent = new Intent(BabbleDetailActivity.this,ReportActivity.class);
                intent.putExtra("id",activityBean.id + "");
                intent.putExtra("intoFlag",2);
                if("image".equals(activityBean.mediaType)){
                    intent.putExtra("path",activityBean.mediaPaths);
                } else if("video".equals(activityBean.mediaType)){
                    intent.putExtra("path",activityBean.thumbnailUrl);
                }
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(BabbleDetailActivity.this);
                reportDialog.dismiss();
                break;
        }
    }

    private void initPop(){
        popupWindow = new PopupWindow(this);
        popupWindow.setContentView(viewComment);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0x00000000);
        popupWindow.setBackgroundDrawable(dw);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);

    }

    private void showReportDialog(){
        if(reportDialog == null){
            LayoutInflater inflater = LayoutInflater.from(this);
            View v = inflater.inflate(R.layout.view_report_dialog, null);
            reportDialog = new Dialog(this, R.style.CustomDialogStyle);
            reportDialog.setCanceledOnTouchOutside(false);
            reportDialog.setContentView(v, new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT));
            TextView tvBubble = (TextView) v.findViewById(R.id.dialog_report_bubble);
            TextView tvPicture = (TextView) v.findViewById(R.id.dialog_report_picture);
            tvBubble.setOnClickListener(this);
            tvPicture.setOnClickListener(this);
        }
        reportDialog.show();
    }

    /** 请求评论列表*/
    private void dorequestCommenList(){
        params = new AjaxParams();
        params.put("activityId",activityBean.id+"");
        httpRequest.addHeader("Cookie", "userLoginID=" + userLoginID);
        httpRequest.get(Urls.url_comment_list,params,callBack,5);
    }

    /** 评论*/
    private void dorequestComment(String comment){
        showLoading();
        params = new AjaxParams();
        params.put("activityId",activityBean.id+"");
        params.put("replyerId",activityBean.userId+"");
        params.put("content",comment+"");
        httpRequest.addHeader("Cookie", "userLoginID=" + userLoginID);
        httpRequest.post(Urls.url_comment,params,callBack,6);
    }

    /** 加热接口*/
    private void dorequestFire(String uid){
        showLoading();
        params = new AjaxParams();
        params.put("activityId",uid+"");
        httpRequest.addHeader("Cookie", "userLoginID=" + userLoginID);
        httpRequest.post(Urls.url_fire,params,callBack,1);
    }

    /** 删除接口*/
    private void dorequestDelete(String uid){
        showLoading();
        params = new AjaxParams();
        params.put("activityId",uid+"");
        httpRequest.addHeader("Cookie", "userLoginID=" + userLoginID);
        httpRequest.post(Urls.url_delete_activity,params,callBack,2);
    }

    @Override
    protected void handlerBean(int requestCode, BaseBean baseBean) {
        super.handlerBean(requestCode, baseBean);
        if(baseBean.success) {
            String data = String.valueOf(baseBean.data);
            switch (requestCode){
                case 5://评论列表
                    Type type = new TypeToken<List<CommentBean>>(){}.getType();
                    listRequest = gson.fromJson(data,type);
                    listComment.addAll(listRequest);
                    adapter.notifyDataSetChanged();
                    tvConmmentNum.setText(listRequest.size()+"");
                    popupWindow.dismiss();
                    if(intoFlag == 1){//直接显示评论
                        handler.sendEmptyMessageDelayed(0,500);
                    }
                    break;
                case 6://评论
                    intoFlag = 0;
                    listComment.clear();
                    showLoading();
                    dorequestCommenList();
                    break;
                case 1://加热
                    try {
                        JSONObject obj = new JSONObject(data);
                        int activityId = obj.optInt("activityId");
                        int heatValue = obj.optInt("heatValue");
                        tvFire.setText(heatValue+"");
                        activityBean.heated = 1;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case 2:
                    try {
                        JSONObject obj = new JSONObject(data);
                        int activityId = obj.optInt("activityId");
                        this.finish();
                        AnimUtil.pushRightInAndOut(this);
                        this.sendBroadcast(new Intent("new_bubble"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        } else {
            if(!TextUtils.isEmpty(baseBean.errMsg)){
                showToast(baseBean.errMsg);
            }
        }
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            etComment.setFocusable(true);
            etComment.setFocusableInTouchMode(true);
            etComment.requestFocus();
            KeyBoard.showKeyBoard(BabbleDetailActivity.this,etComment);
            InputMethodManager inputManager = (InputMethodManager) etComment
                    .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.showSoftInput(etComment, 0);
            popupWindow.showAtLocation(BabbleDetailActivity.this.getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
        }
    };

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }
}
